package com.hww.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Objects;

/**
 * @author: youdao.hww
 * @Date: 1/8/24
 * @Desc:
 */
@Configuration
public class AutoFillFieldValueConfig implements MetaObjectHandler {

    @Autowired
    private LoginInfoHelper loginInfoHelper;

    private static final String createBy = "createBy";
    private static final String updateBy = "updateBy";
    private static final String createTime = "createTime";
    private static final String updateTime = "updateTime";

    private static final String orgId = "orgId";

    private static final String isDeleted = "isDeleted";


    @Override
    public void insertFill(MetaObject metaObject) {
        SystemLoginInfo loginInfo = loginInfoHelper.getLoginInfo();
        if (Objects.nonNull(loginInfo)) {
            this.setFieldValByName(createTime, new Date(), metaObject);
            this.setFieldValByName(updateTime, new Date(), metaObject);
            this.setFieldValByName(createBy, loginInfo.getUserId(), metaObject);
            this.setFieldValByName(updateBy, loginInfo.getUserId(), metaObject);
            this.setFieldValByName(isDeleted, 0, metaObject);
            this.setFieldValByName(orgId, loginInfo.getOrgId(), metaObject);
        }


    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SystemLoginInfo loginInfo = loginInfoHelper.getLoginInfo();
        if (Objects.nonNull(loginInfo)) {
            this.setFieldValByName(updateTime, new Date(), metaObject);
            this.setFieldValByName(updateBy, loginInfo.getUserId(), metaObject);
        }
    }


}
